package com.knoya.chejian.pda.myclass

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.FileProvider
import com.knoya.chejian.pda.R
import com.knoya.chejian.pda.minterface.OnUserDataInterface
import com.knoya.chejian.pda.util.HttpUtil
import com.knoya.chejian.pda.util.JsonUtil
import com.knoya.chejian.pda.util.Myutil
import com.knoya.chejian.pda.util.PermissionUtils
import com.yanzhenjie.permission.PermissionListener
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.File

/**
 * Created by Administrator on 2017/2/25/025.
 * 作者：刘洋
 * 此类为更新版本
 */

class UpdataInfo(private val mconetxt: Context, private val mistrue: Boolean, private val sp: SharedPreferences) {

    private var updatedialog: AlertDialog? = null
    val updateInfo = UpdateInfoBean()
    /**
     * 获取当前版本的版本号
     *
     * @return 当前版本号，未成功则返回 版本号未知
     */
    private val version: String
        get() {
            try {
                val packageManager = mconetxt.packageManager
                val packageInfo = packageManager.getPackageInfo(
                        mconetxt.packageName, 0)
                return packageInfo.versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                return "版本号未知"
            }

        }

    var sizi = ""

    /**
     * 网络访问获取版本信息
     */
    fun show() {
        HttpUtil.getUpdateInfo(mconetxt, object : OnUserDataInterface {
            override fun onUserData(data: String) {

                val info = data.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                updateInfo.version = info[1]
                updateInfo.description = info[2]
                updateInfo.url = info[3]
                if(info.size>4) {
                    updateInfo.name = info[4]
                }
                val isViewsion = version
                if (updateInfo.version == isViewsion) {
                    Myutil.MyTost("已是最新版本")
                    return
                }
                val s = "当前版本：" + isViewsion + "   最新版本为：" + updateInfo.version + "   更新包大小" + sizi
                quitdialog(s, updateInfo)
            }

            override fun onNot(throwable: String) {
                if (updatedialog != null) {
                    updatedialog!!.dismiss()
                }
            }
        })
    }



    /**
     * 检测到当前版本号低于服务器，则弹出dialog询问是否更新
     *
     * @param s 询问textview显示的文字
     */
    private fun quitdialog(s: String, updateInfoBean: UpdateInfoBean) {
        val quitdialog = AlertDialog.Builder(mconetxt).create()
        quitdialog.show()
        quitdialog.window!!.setContentView(R.layout.dialog_upda)
        val tv_quite_confirm = quitdialog.findViewById<View>(R.id.tv_quite_confirm) as TextView
        val tv_data = quitdialog.findViewById<View>(R.id.tv_data) as TextView
        tv_data.text = updateInfoBean.description
        val tv_title = quitdialog.findViewById<View>(R.id.tv_title) as TextView
        tv_title.text = s
        quitdialog.setCanceledOnTouchOutside(false)
        val activity = mconetxt as Activity
        tv_quite_confirm.setOnClickListener {
            if (Build.VERSION.SDK_INT < 26) {
                PermissionUtils.isupdateapk(activity, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        showupdatedialog(updateInfoBean.url)
                        quitdialog.dismiss()
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法下载apk")
                    }
                })
            } else {
                if (!activity.packageManager.canRequestPackageInstalls()) {
                    val packageURI = Uri.parse("package:" + activity.packageName)
                    //注意这个是8.0新API
                    val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                    activity.startActivityForResult(intent, 10086)
                } else {
                    PermissionUtils.isupdateapk(activity, object : PermissionListener {
                        override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                            showupdatedialog(updateInfoBean.url)
                            quitdialog.dismiss()
                        }

                        override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                            Myutil.MyTost("没有权限，无法下载apk")
                        }
                    })
                }
            }
        }
        if (!mistrue) {
//            quitdialog.setOnKeyListener { dialog, keyCode, event ->
//                activity.finish()
//                false
//            }
        }
    }

    /**
     * 下载进度对话框，并下载apk
     *
     * @param url 在检测版本是获得的服务器apk的url
     */
    private fun showupdatedialog(url: String) {
        val f = File(Environment.getExternalStorageDirectory().toString() + "/erp/"+updateInfo.name)
        if(f.exists()){
            val quitdialog = AlertDialog.Builder(mconetxt).create()
            quitdialog.show()
            quitdialog.window!!.setContentView(R.layout.dialog_upda)
            val tv_quite_confirm = quitdialog.findViewById<View>(R.id.tv_quite_confirm) as TextView
            tv_quite_confirm.text="安装"
            val tv_data = quitdialog.findViewById<View>(R.id.tv_data) as TextView
            tv_data.text = "apk已经下载，点击安装"
            val tv_title = quitdialog.findViewById<View>(R.id.tv_title) as TextView
            tv_title.text = "提示"
            quitdialog.setCanceledOnTouchOutside(false)
            tv_quite_confirm.setOnClickListener {
                update()
                quitdialog.dismiss()
            }
            if(mistrue) {
//                quitdialog.setOnKeyListener { dialog, keyCode, event ->
//                    val activity = mconetxt as Activity
//                    activity.finish()
//                    false
//                }
            }
        }else {
            val updatedialog = AlertDialog.Builder(mconetxt).create()
            updatedialog.show()
            updatedialog.setCanceledOnTouchOutside(false)
            updatedialog.window!!.setContentView(R.layout.dialog_update)
            val tv_schedule = updatedialog.findViewById<View>(R.id.tv_schedule) as TextView
            val pb_progressbar = updatedialog.findViewById<View>(R.id.pb_progressbar) as ProgressBar
            HttpUtil.showUpdateInfo(mconetxt, url, Environment.getExternalStorageDirectory().toString() + "/erp/" + updateInfo.name, pb_progressbar, tv_schedule, object : OnUserDataInterface {
                override fun onUserData(data: String) {
                    update()
                    updatedialog.dismiss()
                }

                override fun onNot(throwable: String) {}
            })
            updatedialog.setOnKeyListener { dialog, keyCode, event ->
                val activity = mconetxt as Activity
                activity.finish()
                false
            }
        }
    }

    /**
     * 下载成功后安装下载好的apk程序
     */
    fun update() {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val contentUri = FileProvider.getUriForFile(mconetxt, "com.knoya.chejian.pda.fileProvider", File(Environment.getExternalStorageDirectory().toString() + "/erp/"+updateInfo.name))
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(File(Environment.getExternalStorageDirectory().toString() + "/erp/"+updateInfo.name)), "application/vnd.android.package-archive")
        }
        if (mconetxt.packageManager.queryIntentActivities(intent, 0).size > 0) {
            mconetxt.startActivity(intent)
        }
    }

}
